package io.xccit.race.controller;

import io.xccit.common.annotation.Log;
import io.xccit.common.core.controller.BaseController;
import io.xccit.common.core.domain.AjaxResult;
import io.xccit.common.core.page.TableDataInfo;
import io.xccit.common.enums.BusinessType;
import io.xccit.race.domain.RaceCompetitionResult;
import io.xccit.race.service.IRaceCompetitionResultService;
import io.xccit.race.service.MinioService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 竞赛成果物Controller
 * 
 * @author ywx
 * @date 2025-10-13
 */
@RestController
@RequestMapping("/race/competitionResult")
public class RaceCompetitionResultController extends BaseController {
    
    @Autowired
    private IRaceCompetitionResultService raceCompetitionResultService;

    /**
     * 查询竞赛成果物列表
     */
    @PreAuthorize("@ss.hasPermi('race:competitionResult:list')")
    @GetMapping("/list")
    public TableDataInfo list(RaceCompetitionResult raceCompetitionResult) {
        startPage();
        List<RaceCompetitionResult> list = raceCompetitionResultService.selectRaceCompetitionResultList(raceCompetitionResult);
        return getDataTable(list);
    }

    /**
     * 导出竞赛成果物列表
     */
    @PreAuthorize("@ss.hasPermi('race:competitionResult:export')")
    @Log(title = "竞赛成果物", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RaceCompetitionResult raceCompetitionResult) {
        List<RaceCompetitionResult> list = raceCompetitionResultService.selectRaceCompetitionResultList(raceCompetitionResult);
        // TODO: 实现导出功能
    }

    /**
     * 获取竞赛成果物详细信息
     */
    @PreAuthorize("@ss.hasPermi('race:competitionResult:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(raceCompetitionResultService.selectRaceCompetitionResultById(id));
    }

    /**
     * 新增竞赛成果物
     */
    @PreAuthorize("@ss.hasPermi('race:competitionResult:add')")
    @Log(title = "竞赛成果物", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RaceCompetitionResult raceCompetitionResult) {
        return toAjax(raceCompetitionResultService.insertRaceCompetitionResult(raceCompetitionResult));
    }

    /**
     * 修改竞赛成果物
     */
    @PreAuthorize("@ss.hasPermi('race:competitionResult:edit')")
    @Log(title = "竞赛成果物", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RaceCompetitionResult raceCompetitionResult) {
        return toAjax(raceCompetitionResultService.updateRaceCompetitionResult(raceCompetitionResult));
    }

    /**
     * 删除竞赛成果物
     */
    @PreAuthorize("@ss.hasPermi('race:competitionResult:remove')")
    @Log(title = "竞赛成果物", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(raceCompetitionResultService.deleteRaceCompetitionResultByIds(ids));
    }

    /**
     * 根据竞赛ID查询成果物列表
     */
    @PreAuthorize("@ss.hasPermi('race:competitionResult:list')")
    @GetMapping("/competition/{competitionId}")
    public AjaxResult getByCompetitionId(@PathVariable Long competitionId) {
        List<RaceCompetitionResult> list = raceCompetitionResultService.selectRaceCompetitionResultByCompetitionId(competitionId);
        return success(list);
    }

    /**
     * 根据报名记录ID查询成果物
     */
    @PreAuthorize("@ss.hasPermi('race:competitionResult:query')")
    @GetMapping("/signup/{signupId}")
    public AjaxResult getBySignupId(@PathVariable Long signupId) {
        RaceCompetitionResult result = raceCompetitionResultService.selectRaceCompetitionResultBySignupId(signupId);
        return success(result);
    }

    /**
     * 根据用户ID查询成果物列表
     */
    @PreAuthorize("@ss.hasPermi('race:competitionResult:list')")
    @GetMapping("/user/{userId}")
    public AjaxResult getByUserId(@PathVariable Long userId) {
        List<RaceCompetitionResult> list = raceCompetitionResultService.selectRaceCompetitionResultByUserId(userId);
        return success(list);
    }

    /**
     * 统计成果物数量
     */
    @PreAuthorize("@ss.hasPermi('race:competitionResult:list')")
    @GetMapping("/count")
    public AjaxResult getCount() {
        Long count = raceCompetitionResultService.selectRaceCompetitionResultCount();
        return success(count);
    }

    /**
     * 统计审核状态分布
     */
    @PreAuthorize("@ss.hasPermi('race:competitionResult:list')")
    @GetMapping("/auditStatus/distribution")
    public AjaxResult getAuditStatusDistribution() {
        List<Map<String, Object>> distribution = raceCompetitionResultService.selectAuditStatusDistribution();
        return success(distribution);
    }

    /**
     * 统计竞赛成果物数量
     */
    @PreAuthorize("@ss.hasPermi('race:competitionResult:list')")
    @GetMapping("/competition/{competitionId}/count")
    public AjaxResult getResultCountByCompetitionId(@PathVariable Long competitionId) {
        Long count = raceCompetitionResultService.selectResultCountByCompetitionId(competitionId);
        return success(count);
    }

    /**
     * 审核成果物
     */
    @PreAuthorize("@ss.hasPermi('race:competitionResult:audit')")
    @Log(title = "竞赛成果物审核", businessType = BusinessType.UPDATE)
    @PutMapping("/audit")
    public AjaxResult audit(@RequestBody RaceCompetitionResult raceCompetitionResult) {
        return toAjax(raceCompetitionResultService.auditRaceCompetitionResult(raceCompetitionResult));
    }

    /**
     * 提交成果物
     */
    @PreAuthorize("@ss.hasPermi('race:competitionResult:submit')")
    @Log(title = "提交竞赛成果物", businessType = BusinessType.INSERT)
    @PostMapping("/submit")
    public AjaxResult submit(@RequestBody RaceCompetitionResult raceCompetitionResult) {
        return toAjax(raceCompetitionResultService.submitRaceCompetitionResult(raceCompetitionResult));
    }

    @Autowired
    private MinioService minioService;
    
    /**
     * 上传成果物文件
     */
    @PreAuthorize("@ss.hasPermi('race:competitionResult:submit')")
    @Log(title = "上传竞赛成果物", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file,
                            @RequestParam("competitionId") Long competitionId,
                            @RequestParam("signupId") Long signupId,
                            @RequestParam("resultName") String resultName,
                            @RequestParam(value = "resultDescription", required = false) String resultDescription) {
        try {
            // 检查文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || !originalFilename.toLowerCase().endsWith(".zip")) {
                return error("只支持上传ZIP格式的压缩包文件");
            }
            
            // 检查文件大小（限制为100MB）
            if (file.getSize() > 100 * 1024 * 1024) {
                return error("文件大小不能超过100MB");
            }
            
            // 上传文件到MinIO
            String fileUrl = minioService.upload(file);
            
            // 计算文件MD5值
            String fileMd5 = calculateFileMD5(file);
            
            // 创建成果物记录
            RaceCompetitionResult result = new RaceCompetitionResult();
            result.setCompetitionId(competitionId);
            result.setSignupId(signupId);
            result.setResultName(resultName);
            result.setResultDescription(resultDescription);
            result.setFilePath(fileUrl);
            result.setFileSize(file.getSize());
            result.setFileMd5(fileMd5);
            
            int insertResult = raceCompetitionResultService.submitRaceCompetitionResult(result);
            if (insertResult > 0) {
                AjaxResult ajax = AjaxResult.success("成果物上传成功");
                ajax.put("fileUrl", fileUrl);
                ajax.put("fileSize", file.getSize());
                ajax.put("fileMd5", fileMd5);
                return ajax;
            } else {
                return error("成果物记录保存失败");
            }
            
        } catch (Exception e) {
            return error("文件上传失败：" + e.getMessage());
        }
    }
    
    /**
     * 计算文件MD5值
     */
    private String calculateFileMD5(MultipartFile file) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(file.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (Exception e) {
            return "";
        }
    }
}
